package com.dartfar.permission.action;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.dartfar.base.action.BaseAction;
import com.dartfar.base.model.Function;
import com.dartfar.base.service.FunctionService;
import com.dartfar.base.vo.TreeVo;
import com.dartfar.menu.model.Menu;
import com.dartfar.menu.service.MenuService;
import com.dartfar.permission.model.Permission;
import com.dartfar.permission.service.PermissionService;
import com.dartfar.util.EntityUtils;

@Scope("prototype")
@Component("permissionAction")
public class PermissionAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	static Logger logger = Logger.getLogger(PermissionAction.class);
	
	/**
	 * Service服务
	 */
	@Resource
	private MenuService menuService;
	@Resource
	private FunctionService functionService;
	@Resource
	private PermissionService permissionService;
	
	/**
	 * 传递参数
	 */
	private String roleId;
	private String menuId;
	private String funIds;
	private String flag;
	
	/**
	 * 页面跳转
	 * @return
	 */
	public String show(){
		return "show";
	}
	
	/**
	 * 保存权限
	 */
	public String save(){
		//变量
		flag = "true";
		try{
			//实例化
			Permission permission = new Permission();
			permission.setRoleId(roleId);
			permission.setMenuId(menuId);
			permission.setFunIds(funIds);
			//保存
			permissionService.save(permission);
		}catch (Exception e) {
			// TODO: handle exception
			flag = "false";
			e.printStackTrace();
		}
/*	
		//返回JSON
		String jsonResult = JSONObject.fromObject(flag).toString();
		System.out.println("jsonResult: " + jsonResult);
		try {
			response.getWriter().write(jsonResult);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		return SUCCESS;
	}
	
	/**
	 * 删除权限
	 */
	public void remove(){
		permissionService.removeByRoleId(roleId);
	}
	
	/**
	 * 读取权限树的模块和功能
	 * @return 权限树的Json字符串
	 */
	public String loadTreeData() {
		logger.info("roleId: " + roleId);
		//初始化roleId
		if(roleId == null){
			roleId = "1";
		}
		//主菜单VO对象
		List<TreeVo> treeMainMenuVos = new ArrayList<TreeVo>();
		try{
			//获取所有主菜单
			List<Menu> mainMenus = menuService.getMainMenuLsit();
			//获取所有功能
			List<Function> functions = functionService.getList();

			//遍历主菜单
			for (Iterator<Menu> i = mainMenus.iterator(); i.hasNext();) {
				Menu menu = i.next();
				TreeVo treeMainMenuVo = new TreeVo();
				treeMainMenuVo.setId("m" + menu.getId());
				treeMainMenuVo.setText(menu.getName());
				treeMainMenuVo.setIconCls(menu.getIconCls());
				
				//如果主菜单中存在子菜单
				if (!menu.isLeaf()){
					treeMainMenuVo.setState("open");
					//获取根据主菜单ID获取子菜单列表
					List<Menu> subMenus = menuService.getSubMenuList(menu.getId());
					//子菜单树递归
					List<TreeVo> treeSubMenuVos = menus2Trees(subMenus, 0, functions, roleId);
					treeMainMenuVo.setChildren(treeSubMenuVos);
				}
				treeMainMenuVos.add(treeMainMenuVo);
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		//转化为JSON字符串
		String jsonResult = JSONArray.fromObject(treeMainMenuVos).toString();
		try {
			response.getWriter().write(jsonResult);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 子菜单递归
	 * @param functions 功能列表
	 * @param parentId 父结点ID
	 * @param roleFunctions 角色中的所有功能
	 * @return
	 */
	public List<TreeVo> menus2Trees(List<Menu> menus, int parentId,	List<Function> functions, String roleId) {
		logger.info("roleId: " + roleId);
		List<TreeVo> treeVos = new ArrayList<TreeVo>();
		for (Iterator<Menu> i = menus.iterator(); i.hasNext();) {
			Menu menu = i.next();
			int menuParentId = 0;
			if (menu.getParentMenu() != null) {
				menuParentId = menu.getParentMenu().getId();
			}

			if (parentId == menuParentId) {
				TreeVo treeVo = new TreeVo();
				treeVo.setId("s" + menu.getId());
				treeVo.setText(menu.getName());
				treeVo.setIconCls(menu.getIconCls());
				//如果不是叶子节点，树结点打开
				if (!menu.isLeaf()) {
					treeVo.setState("open");
					//递归下级结点
					List<TreeVo> nextTreeVos = menus2Trees(menus, menu.getId(), functions, roleId);
					treeVo.setChildren(nextTreeVos);
				}else{
					//节点状态为关闭
					treeVo.setState("closed");
					//遍历功能树
					List<TreeVo> treeFunctionVos = functionTrees(functions, roleId, String.valueOf(menu.getId()));
					//把功能树加入子菜单
					treeVo.setChildren(treeFunctionVos);
				}
				treeVos.add(treeVo);
			}
		}
		return treeVos;
	}
	/**
	 * 功能递归
	 * @param functions 功能列表
	 * @return
	 */
	public List<TreeVo> functionTrees(List<Function> functions, String roleId, String m_Id) {
		//根据菜单ID获取 菜单拥有的功能
		List<Permission> perlist = permissionService.getListByRoleIdOrMenuId(roleId, m_Id);
		
		logger.info("perlist: " + perlist.size());
		
		//实例化功能树
		List<TreeVo> treeVos = new ArrayList<TreeVo>();
		//遍历功能列表
		for (Iterator<Function> i = functions.iterator(); i.hasNext();) {
			Function fun = i.next();
			TreeVo treeVo = new TreeVo();
			treeVo.setId("f" + fun.getId());
			treeVo.setText(fun.getDes());
			treeVo.setIconCls(fun.getIconCls());
			
			if(EntityUtils.isNotNull(perlist)){
				//遍历当前菜单拥有的功能权限
				for(Iterator<Permission> p = perlist.iterator(); p.hasNext();){
					Permission per = p.next();
					//如果功能ID存在菜单权限中，结点被选中
					if(EntityUtils.isNotNull(per.getFunIds())){
						String[] funs = per.getFunIds().split(",");
						//遍历功能数组
						for(int f = 0; f < funs.length; f++){
							//判断是否拥有功能
							if(String.valueOf(fun.getId()).equalsIgnoreCase(funs[f]) && m_Id.equalsIgnoreCase(per.getMenuId())){
								treeVo.setChecked(true);
							}
							
							
						}
					}
				}
			}
			
			treeVos.add(treeVo);
		}
		return treeVos;
	}

	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public String getMenuId() {
		return menuId;
	}

	public void setMenuId(String menuId) {
		this.menuId = menuId;
	}

	public String getFunIds() {
		return funIds;
	}

	public void setFunIds(String funIds) {
		this.funIds = funIds;
	}

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}
	
}
